﻿using FileSystem.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace FileSystem.impl.Actions
{
    public class Find_Async : ActionABC, IAction ,INodeVisitor
    {
        private string nodeName;
        private bool executeSucceeded;
        private IResult lastResult;
        private IFSDirectory directory;
        private StringBuilder sb = new StringBuilder();

        public Find_Async(string nodeName)
           :base(new HelpDescription() { Name = "find-async", Description = "find files in current directory." })
        {
            this.nodeName = nodeName;
		}

        //public Find_Async(): base(new HelpDescription() { Name = "find-async", Description = "find files in current directory." })
        //{
            
        //}

       

        #region IAction Members
        private void Searh()
        {
            this.directory.Accept(this);
            if (sb.Length == 0)
            {
               // return new Result(true, "No match found");
            }

           IFSFileSystem fileSystem =  AppResources.getInstance().getFileSystem();
           fileSystem.AsyncResults.Add(new Result(sb.ToString()));
           // return new Result(sb.ToString());
        }

        public override IResult execute()
        {
            this.directory = AppResources.getInstance().getFileSystem().CurrentDirectory;
            Thread calcThread = new Thread(this.Searh);
            calcThread.Start();

            return new Result("Search in progress - You can continue");
           
        }

        #endregion

      
        #region INodeVisitor Members

        public void VisitFile(IFSFile file)
        {
            lastResult = new Result(true, "Given name is not a directory");
            executeSucceeded = true;
        }

        public void VisitDirectory(IFSDirectory directory)
        {
            for (int iNode = 0; iNode < directory.numNodes(); iNode++)
            {
                IFSNode node = directory.getNode(iNode);
                if (node.getName() == nodeName)
                {
                    sb.AppendLine(node.getFQName());
                }
                node.Accept(this);

            }

            executeSucceeded = true;
        }

        public void VisitLink(IFSLink link)
        {
            if (link.GetLinkedNode() != null)
                link.GetLinkedNode().Accept(this);
        }

        #endregion



    }
}
